package eclipse;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class ArrayExercise12 {
    public static void main(String[] args) {
        int[] arr = randomArray();
        System.out.println(Arrays.toString(arr));
        System.out.print("请输入一个数字:");
        int num = new Scanner(System.in).nextInt();
        int index = binarySearch(num, arr);
        System.out.println(index);
    }

    private static int binarySearch(int num, int[] arr) {
        int lo = 0;
        int hi = arr.length - 1;
        int mid;
        while(true){
            mid = (lo + hi) / 2;
            if(lo <= hi){
                if(arr[mid] > num){
                    lo += 1;
                }else if(arr[mid] < num){
                    hi -= 1;
                }else{
                    return mid;
                }

            }else{
                return -1;
            }
        }


    }

    private static int[] randomArray() {
        int len = 5 + new Random().nextInt(6);
        int[] arr = new int[len];
        for(int i = 0; i < arr.length; i++){
            arr[i] = new Random().nextInt(100);
        }
        return arr;
    }
}
